# coding: utf-8

import os
import sys
import subprocess

import logging
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)


initCwd = os.path.dirname(os.path.abspath(__file__))

logging.info("脚本所在路径: %s" % initCwd)


# 编译glog
if os.path.exists(initCwd + "/glog"):

    logging.info("glog正在安装...")

    if not os.path.exists(initCwd + "/glog/out"):
        os.makedirs(initCwd + "/glog/out")

    os.chdir(initCwd + "/glog/out")

    if subprocess.call(["cmake", ".."]) == 0 and subprocess.call(["make", "-j4"]) == 0:
        d = subprocess.Popen("sudo make install", shell=True)
        d.communicate()
        logging.info("glog安装成功!\n")
    else:
        logging.error("glog安装失败!\n")
        sys.exit(-1)


# 编译rapidjson
if os.path.exists(initCwd + "/rapidjson"):

    logging.info("rapidjson正在安装...")

    if not os.path.exists(initCwd + "/rapidjson/out"):
        os.makedirs(initCwd + "/rapidjson/out")

    os.chdir(initCwd + "/rapidjson/out")

    if subprocess.call(["cmake", ".."]) == 0 and subprocess.call(["make", "-j4"]) == 0:
        d = subprocess.Popen("sudo make install", shell=True)
        d.communicate()
        logging.info("rapidjson安装成功!\n")
    else:
        logging.error("rapidjson安装失败!\n")
        sys.exit(-1)


# 编译cpprestsdk
if os.path.exists(initCwd + "/cpprestsdk"):

    logging.info("cpprestsdk正在安装...")

    if not os.path.exists(initCwd + "/cpprestsdk/Release/out"):
        os.makedirs(initCwd + "/cpprestsdk/Release/out")

    os.chdir(initCwd + "/cpprestsdk/Release/out")

    if subprocess.call(["cmake", ".."]) == 0 and subprocess.call(["make", "-j4"]) == 0:
        d = subprocess.Popen("sudo make install", shell=True)
        d.communicate()
        logging.info("cpprestsdk安装成功!\n")
    else:
        logging.error("cpprestsdk安装失败!\n")


# 编译utils
if os.path.exists(initCwd + "/utils"):

    logging.info("utils正在安装...")

    if not os.path.exists(initCwd + "/utils/out"):
        os.makedirs(initCwd + "/utils/out")

    os.chdir(initCwd + "/utils/out")

    if subprocess.call(["cmake", ".."]) == 0 and subprocess.call(["make", "-j4"]) == 0:
        d = subprocess.Popen("sudo make install", shell=True)
        d.communicate()
        logging.info("utils安装成功!\n")
    else:
        logging.error("utils安装失败!\n")
